package hw;

import sk.Util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ModifyPanel extends JPanel implements ActionListener {
    private ATM atm;
    private JButton sureBtn;
    private JButton clearBtn;
    private Icon sureImg = Util.getImageIcon("/images/buttonSure.jpg");
    private Icon clearImg = Util.getImageIcon("/images/buttonOff.jpg");

    private JTextField oldpsw = new JTextField();
    private JTextField newpsw = new JTextField();
    private JTextField repsw = new JTextField();

    public ModifyPanel(ATM atm) {
        this.atm = atm;
        this.setLayout(null);
        this.setOpaque(false);

        JLabel oldlabel = new JLabel("请输入旧密码:");
        oldlabel.setBounds(200, 200, 130, 30);
        oldlabel.setFont(new Font("黑体", Font.BOLD, 16));
        this.add(oldlabel);
        oldpsw.setBounds(350, 200, 150, 30);
        this.add(oldpsw);

        JLabel newlabel = new JLabel("请输入新密码:");
        newlabel.setBounds(200, 250, 130, 30);
        newlabel.setFont(new Font("黑体", Font.BOLD, 16));
        this.add(newlabel);
        newpsw.setBounds(350, 250, 150, 30);
        this.add(newpsw);

        JLabel relabel = new JLabel("请确认新密码:");
        relabel.setBounds(200, 300, 130, 30);
        relabel.setFont(new Font("黑体", Font.BOLD, 16));
        this.add(relabel);
        repsw.setBounds(350, 300, 150, 30);
        this.add(repsw);


        sureBtn = new JButton(sureImg);
        sureBtn.setBounds(200, 400, 140, 50);
        this.add(sureBtn);
        sureBtn.addActionListener(this);

        clearBtn = new JButton(clearImg);
        clearBtn.setBounds(420, 400, 140, 50);
        this.add(clearBtn);
        clearBtn.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == sureBtn) {
            if (oldpsw.getText().equals(atm.getUsers().get(atm.getNum()).getPassword())) {
                if (repsw.getText().equals(newpsw.getText())) {
                    JOptionPane.showMessageDialog(this, "修改密码成功，请重新登录");
                    atm.getUsers().get(atm.getNum()).setPassword(newpsw.getText());
                    FileUtil.writeObject("d:/user.txt", atm.getUsers());
                    atm.switchPanel("login");
                    return;
                } else {
                    JOptionPane.showMessageDialog(this, "确认密码错误");
                }
            } else {
                JOptionPane.showMessageDialog(this, "旧密码输入错误");
            }

        } else if (e.getSource() == clearBtn) {
            atm.switchPanel("menu");
        }
    }
}
